#!/user/bin/env python
# -*- coding: utf-8 -*-
''' 
Author: Sjy
LastEditTime: 2024-09-03 15:55:20
Description: QtCore.QThread 构建多线程开启线程 使用方法参照测试用例
'''

__all__= []


import sys
import time

from PyQt5 import QtCore, QtWidgets


class WorkThread(QtCore.QThread):
    # 自定义信号对象。参数str就代表这个信号可以传一个字符串
    trigger = QtCore.pyqtSignal(dict)
    def __int__(self):
        # 初始化函数   注意 __init__ 不要传参 会报错，待查看具体原因
        super(WorkThread, self).__init__()
    def _set_run(self, runFun):
        self.__runFun = runFun
    def run(self):
        #重写线程执行的run函数
        #触发自定义信号
        while True:
            reValue = self.__runFun() or {}
            isBreak = reValue.get("break", False)
            if isBreak:
                break
            params = reValue.get("params", "")
            delay = reValue.get("delay", 0)
            time.sleep(delay)
            self.trigger.emit(params)
            # QtCore.QCoreApplication.processEvents()  # 处理事件循环 待议

class CreateThread():
    def __init__(self, runFun, done):
        self.__work = WorkThread()
        self.__work._set_run(runFun)
        self.__work.trigger.connect(done)
    def start(self):
        self.__work.start()


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    class Ui_Form(object):
        def setupUi(self, Form):
            Form.setObjectName("Form")
            Form.resize(498, 331)
            self.runButton = QtWidgets.QPushButton(Form)
            self.runButton.setGeometry(QtCore.QRect(190, 30, 75, 23))
            self.runButton.setObjectName("runButton")
            self.listWidget = QtWidgets.QListWidget(Form)
            self.listWidget.setGeometry(QtCore.QRect(30, 70, 431, 192))
            self.listWidget.setObjectName("listWidget")

            self.retranslateUi(Form)
            QtCore.QMetaObject.connectSlotsByName(Form)

        def retranslateUi(self, Form):
            _translate = QtCore.QCoreApplication.translate
            Form.setWindowTitle(_translate("Form", "QtCore.QThread Example"))
            self.runButton.setText(_translate("Form", "Run"))
    class MyMainForm(QtWidgets.QMainWindow, Ui_Form):
        def __init__(self, parent=None):
            super(MyMainForm, self).__init__(parent)
            self.setupUi(self)

            self.__number = 20
            # 实例化线程对象
            self.work = CreateThread(lambda *args, **kwargs:self.run(*args, **kwargs), lambda *args, **kwargs:self.display(*args, **kwargs))
            self.runButton.clicked.connect(self.execute)
            
        def run(self, *args, **kwargs):
            self.__number -= 1
            if self.__number <= 0:
                return {
                    "break": True,
                }
            return {
                "params": {"value":str(self.__number)}, # 传递参数
                "delay":1, # 延迟执行
                "break": False, # 是否结束线程
            }
        def execute(self):
            # 启动线程
            self.work.start()
        def display(self, params:dict={}):
            value = params.get("value", "")
            # 由于自定义信号时自动传递一个字符串参数，所以在这个槽函数中要接受一个参数
            self.listWidget.addItem(value)
    myWin = MyMainForm()
    myWin.show()
    sys.exit(app.exec_())